package com.test.mytest.qr;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JTextField;
import javax.swing.UIManager;

import com.google.zxing.NotFoundException;
import com.test.mytest.javacv.JavacvService;
import com.test.mytest.javacv.JavacvService.BeforePainListener;

import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.event.ActionEvent;

public class SaomaTestApp {

	private JFrame frame;
	private JTextField textField;
	private JavacvService javacvService;
	private JPanel panel_1;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
					SaomaTestApp window = new SaomaTestApp();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public SaomaTestApp() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 493, 483);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JPanel panel = new JPanel();
		frame.getContentPane().add(panel, BorderLayout.NORTH);
		
		textField = new JTextField();
		panel.add(textField);
		textField.setColumns(50);
		
		JButton button = new JButton("扫码");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				javacvService.pause(true);
				javacvService.play(panel_1);
			}
		});
		panel.add(button);
		
		panel_1 = new JPanel();
		frame.getContentPane().add(panel_1, BorderLayout.CENTER);
		javacvService = new JavacvService();
		javacvService.setClassiferName(null);
		javacvService.start();
		javacvService.addBeforePainListener(new BeforePainListener() {
			@Override
			public void beforePain(BufferedImage image) {
				try {
					String decode = QRCodeUtil.decode(image);
					System.out.println("decode==="+decode);
					if(decode==null||decode.trim().equals("")){
						return;
					}
					textField.setText(decode);
					javacvService.pause(false);
				} catch (Exception e) {
//					e.printStackTrace();
				}
			}
		});
	}

}
